<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
    <script>
        axios.interceptors.request.use((config) => {

            if (typeof cancel === 'function') {
                cancel('取消请求')
            }
            config.cancelToken = new axios.CancelToken(function executor(c) {
                cancel = c;
            })
        })

        axios.interceptors.response.use(response => {
            cancel = null
            console.log('请求1成功了', response.data)
            // 中断promise链
            return new Promise(() => { })
        }, error => {
            cancel = null
            return Promise.reject(error)
        })



        let cancel//用于保存取消请求的函数
        function getProducts1() {

            if (typeof cancel === 'function') {
                cancel('取消请求')
            }

            axios({
                url: 'http://localhost:4000/products1',
                cancelToken: new axios.CancelToken(function executor(c) {
                    cancel = c;
                })
            }).then(response => {
                cancel = null
                console.log('请求1成功了', response.data)
            }, error => {

                if (axios.isCancel(error)) {
                    console.log('请求1取消的错误', error.message)
                } else {
                    cancel = null
                    console.log('请求1失败了', error.message, error) // 请求1失败了 强制取消请求 Cancel {message: "强制取消请求"}

                }
            })
        }

        function getProducts2() {
            axios({
                url: 'http://localhost:4000/products2'
            }).then(
                response => {
                    console.log('请求2成功了', response.data)
                })
        }
        function cancelReq() {
            if (typeof cancel === 'function') {
                cancel('强制取消请求')
            } else {
                console.log('没有可取消的请求')
            }
        }
    </script>
</body>

</html>